package com.simon.seckill.intercept;

import com.simon.seckill.Entities.RequestRecords;
import com.simon.seckill.Exceptions.SeckillExceptions;
import com.simon.seckill.cache.UserBlackListCache;
import com.simon.seckill.conf.SystemConf;
import com.simon.seckill.constant.CommonConstant;
import com.simon.seckill.unit.RedisUtil;
import com.simon.seckill.unit.RestResultUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.List;

public class UserInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserBlackListCache userBlackListCache;

    @Autowired
    private SystemConf systemConf;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String phone = request.getParameter("phone");

        // 该用户是否在黑名单中
        if (userBlackListCache.isIn(phone)) {
            //throw new SeckillExceptions("你已经被拉黑了");
            return false;
        }

        // 查出该用户的访问记录
        List<RequestRecords> requestRecordsList =
                redisUtil.lrange(getKey(phone), 0, systemConf.getUserBlackTimes()-1, RequestRecords.class);

        if (requestRecordsList.size()+1>=systemConf.getUserBlackTimes()&&
                (System.currentTimeMillis()-requestRecordsList.get(requestRecordsList.size()-1).getTimestamp()<
                        systemConf.getUserBlackSeconds()*1000)) {

            // 超过了规定秒数内规定访问次数，进行拉黑
            userBlackListCache.add(phone);

            // 清除该用户的访问记录
            redisUtil.delete(getKey(phone));

            //throw new SeckillExceptions("你已经被拉黑了");
            return false;
        } else {
            // 添加访问记录
            RequestRecords requestRecords = new RequestRecords();
            requestRecords.setPhone(phone);
            requestRecords.setTimestamp(System.currentTimeMillis());
            redisUtil.lpush(getKey(phone), requestRecords);
        }

        return true;
    }

    private String getKey(String phone) {
        return MessageFormat.format(CommonConstant.RedisKey.USER_REQUEST_TIMES, new Object[]{phone});
    }
}
